﻿@namespace Oqtane.Modules.Admin.Users
@inherits ModuleBase
@inject NavigationManager NavigationManager
@inject IUserService UserService
@inject IProfileService ProfileService
@inject ISettingService SettingService

@if (PageState.User != null && photofileid != -1)
{
    <img src="@(ContentUrl(photofileid))" alt="@displayname" style="max-width: 400px" class="rounded-circle mx-auto d-block">
}
else
{
    <br />
}
<TabStrip>
    <TabPanel Name="Identity">
        @if (profiles != null)
        {
            <table class="table table-borderless">
                <tr>
                    <td>
                        <label class="control-label">Username: </label>
                    </td>
                    <td>
                        <input class="form-control" @bind="@username" readonly />
                    </td>
                </tr>
                <tr>
                    <td>
                        <label class="control-label">Password: </label>
                    </td>
                    <td>
                        <input type="password" class="form-control" @bind="@password" />
                    </td>
                </tr>
                <tr>
                    <td>
                        <label class="control-label">Confirm Password: </label>
                    </td>
                    <td>
                        <input type="password" class="form-control" @bind="@confirm" />
                    </td>
                </tr>
                <tr>
                    <td>
                        <label class="control-label">Email: </label>
                    </td>
                    <td>
                        <input class="form-control" @bind="@email" />
                    </td>
                </tr>
                <tr>
                    <td>
                        <label class="control-label">Full Name: </label>
                    </td>
                    <td>
                        <input class="form-control" @bind="@displayname" />
                    </td>
                </tr>
                <tr>
                    <td>
                        <label class="control-label">Photo: </label>
                    </td>
                    <td>
                        <FileManager FileId="@photofileid" @ref="filemanager" />
                    </td>
                </tr>
                <tr>
                    <td>
                        <label class="control-label">Is Deleted? </label>
                    </td>
                    <td>
                        <select class="form-control" @bind="@isdeleted">
                            <option value="True">Yes</option>
                            <option value="False">No</option>
                        </select>
                    </td>
                </tr>
            </table>
        }
    </TabPanel>
    <TabPanel Name="Profile">
        @if (profiles != null)
        {
        <table class="table table-borderless">
            @foreach (Profile profile in profiles)
            {
                var p = profile;
                if (p.Category != category)
                {
                    <tr>
                        <th colspan="2" style="text-align: center;">
                            @p.Category
                        </th>
                    </tr>
                    category = p.Category;
                }
                <tr>
                    <td>
                        <label for="@p.Name" class="control-label">@p.Title: </label>
                    </td>
                    <td>
                        <input class="form-control" maxlength="@p.MaxLength" value="@GetProfileValue(p.Name, p.DefaultValue)" placeholder="@p.Description" @onchange="@(e => ProfileChanged(e, p.Name))" />
                    </td>
                </tr>
            }
        </table>
        }
    </TabPanel>
</TabStrip>

<button type="button" class="btn btn-primary" @onclick="SaveUser">Save</button>
<NavLink class="btn btn-secondary" href="@NavigateUrl()">Cancel</NavLink>
<br /><br />
<AuditInfo CreatedBy="@createdby" CreatedOn="@createdon" ModifiedBy="@modifiedby" ModifiedOn="@modifiedon" DeletedBy="@deletedby" DeletedOn="@deletedon"></AuditInfo>

@code {
    private int userid;
    private string username = string.Empty;
    private string password = string.Empty;
    private string confirm = string.Empty;
    private string email = string.Empty;
    private string displayname = string.Empty;
    private FileManager filemanager;
    private int photofileid = -1;
    private List<Profile> profiles;
    private Dictionary<string, string> settings;
    private string category = string.Empty;
    private string createdby;
    private DateTime createdon;
    private string modifiedby;
    private DateTime modifiedon;
    private string deletedby;
    private DateTime? deletedon;
    private string isdeleted;

    public override SecurityAccessLevel SecurityAccessLevel => SecurityAccessLevel.Admin;

    protected override async Task OnInitializedAsync()
    {
        try
        {
            profiles = await ProfileService.GetProfilesAsync(PageState.Site.SiteId);

            userid = Int32.Parse(PageState.QueryString["id"]);
            var user = await UserService.GetUserAsync(userid, PageState.Site.SiteId);
            if (user != null)
            {
                username = user.Username;
                email = user.Email;
                displayname = user.DisplayName;

                if (user.PhotoFileId != null)
                {
                    photofileid = user.PhotoFileId.Value;
                }

                settings = await SettingService.GetUserSettingsAsync(user.UserId);
                createdby = user.CreatedBy;
                createdon = user.CreatedOn;
                modifiedby = user.ModifiedBy;
                modifiedon = user.ModifiedOn;
                deletedby = user.DeletedBy;
                deletedon = user.DeletedOn;
                isdeleted = user.IsDeleted.ToString();
            }
        }
        catch (Exception ex)
        {
            await logger.LogError(ex, "Error Loading User {UserId} {Error}", userid, ex.Message);
            AddModuleMessage("Error Loading User", MessageType.Error);
        }
    }

    private string GetProfileValue(string SettingName, string DefaultValue)
        => SettingService.GetSetting(settings, SettingName, DefaultValue);

    private async Task SaveUser()
    {
        try
        {
            if (username != string.Empty && email != string.Empty)
            {
                if (password == confirm)
                {
                    var user = await UserService.GetUserAsync(userid, PageState.Site.SiteId);
                    user.SiteId = PageState.Site.SiteId;
                    user.Username = username;
                    user.Password = password;
                    user.Email = email;
                    user.DisplayName = string.IsNullOrWhiteSpace(displayname) ? username : displayname;
                    user.PhotoFileId = null;
                    photofileid = filemanager.GetFileId();

                    if (photofileid != -1)
                    {
                        user.PhotoFileId = photofileid;
                    }

                    user.IsDeleted = (isdeleted == null ? true : Boolean.Parse(isdeleted));

                    user = await UserService.UpdateUserAsync(user);
                    await SettingService.UpdateUserSettingsAsync(settings, user.UserId);
                    await logger.LogInformation("User Saved {User}", user);

                    NavigationManager.NavigateTo(NavigateUrl());
                }
                else
                {
                    AddModuleMessage("Passwords Entered Do Not Match", MessageType.Warning);
                }
            }
            else
            {
                AddModuleMessage("You Must Provide A Username, Password, and Email Address", MessageType.Warning);
            }
        }
        catch (Exception ex)
        {
            await logger.LogError(ex, "Error Saving User {Username} {Email} {Error}", username, email, ex.Message);
            AddModuleMessage("Error Saving User", MessageType.Error);
        }
    }

    private void ProfileChanged(ChangeEventArgs e, string SettingName)
    {
        var value = (string)e.Value;
        settings = SettingService.SetSetting(settings, SettingName, value);
    }

}
